package org.iqiyi.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.iqiyi.entity.VideoEntity;
import org.iqiyi.mapper.VideoMapper;
import org.iqiyi.service.VideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author huqi
 * @since 2021-04-17
 */
@Service
public class VideoServiceImpl extends ServiceImpl<VideoMapper, VideoEntity> implements VideoService {
    @Value("${file.path}")
    private String filePath;
    public List<VideoEntity> selectAll(String typeName) {
        return baseMapper.selectAll(typeName);
    }

    @Override
    public int insert(VideoEntity videoEntity) {
        videoEntity.setDataActive(0);
        videoEntity.setIsShow("1");
        videoEntity.setCreateTime(DateUtil.now());
        return baseMapper.insert(videoEntity);
    }

    @Override
    public void getVideo(Long id, HttpServletResponse response) throws IOException {
        VideoEntity videoEntity = this.getOne(new QueryWrapper<VideoEntity>()
                .eq(VideoEntity.ID,id));
        String videoUrl = videoEntity.getVideoUrl();
        FileInputStream fileInputStream = new FileInputStream(filePath+"/"+videoUrl);
        //获取输入流缓冲区
        FileChannel inputChannel = fileInputStream.getChannel();
        ServletOutputStream httpServletResponse = response.getOutputStream();
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        while(true){
            // 读取缓冲区中的内容
            int i=inputChannel.read(byteBuffer);
            // 拿到内容后转成可读模式
            byteBuffer.flip();
            response.setContentType("application/video");
            httpServletResponse.write(byteBuffer.array());
            byteBuffer.clear();
            if(i==-1){
                break;
            }
        }
        inputChannel.close();
    }


}
